package com.weixun.admin.filter;

import com.weixun.comm.model.vo.Staff;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SessionFilter implements Filter {
    @Override
    public void destroy() {
        // 过滤器销毁，一般是释放资源
    }
    /**
     * 某些url需要登陆才能访问（session验证过滤器）
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //获取请求的url
        String URL = request.getRequestURL().toString();
        // 不过滤的uri,验证码和登录页面不过滤
        String[] notFilter = new String[] { "/code", "/index"};

        // 是否过滤
        boolean doFilter = true;
        for (String s : notFilter) {
            if (URL.indexOf(s) != -1) {
                // 如果uri中包含不过滤的uri，则不进行过滤
                doFilter = false;
                break;
            }
        }
        if (doFilter) {
            //获取session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            Staff user =(Staff)session.getAttribute("user");
            //判断session是否过期
            if (user == null) {
                String errors = "您还没有登录，或者session已过期。请先登陆!";
                request.setAttribute("Message", errors);
                //跳转至登录页面
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                filterChain.doFilter(request, response);
            }
        }
        else
        {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // 初始化操作，读取web.xml中过滤器配置的初始化参数，满足你提的要求不用此方法
    }
}
